﻿using System; 
using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Permissions;
using System.Security.Principal;
using System.Web.Security;
using System.Threading;
using HIS.Utils.Securities;
using KeanuMvc.Reference;
using System.IO;
using HIS.Utils;
using HISModels.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Text;
using System.Globalization;

namespace HIS.Controllers.PatientData {

    public class Default : HIS.Controllers.AppBaseController {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private string UserId = string.Empty;
        private int HiddenPresentAddressId = 0;
        private int HiddenPermanentAddressId = 0;
        private int PrimaryPayerId = 0;
        private int SecondaryPayerId = 0;
        private int TertieryPayerId = 0;
        private int FatherId = 0;
        private int MotherId = 0;
        private int SpouseId = 0;
        private int FamilyRelativeId = 0;
        private int OtherRelativeId = 0;
        string AppointmentId = string.Empty;
        string BookerName = string.Empty;
        string DoctorName = string.Empty;
        string appointdkrpt =string.Empty;
        string doctordkrpt = string.Empty;
        string TempPhone = string.Empty;
        private StringReader stringReader = null;
        private Patient oPatient = null;
        private VPatientData oPatientData = null;
        private Address oPresentAddress = null;
        private Address oPermanentAddress = null;
        private PatientPayer oPatientPrimaryPayer = null;
        private PatientPayer oPatientSecondaryPayer = null;
        private PatientPayer oPatientTertieryPayer = null;
        private FormRegistration.PresentAddress oFormPresentAddress = null;
        private FormRegistration.PermanentAddress oFormPermanentAddress = null;
        private PatientPassId oPatientPassport = null;
        private PatientPassId oPatientVisa = null;
        private PatientPassId oPatientWorkPermit = null;
        private FormRegistration.PatientPassport oFormPatientPassport = null;
        private FormRegistration.PatientVisa oFormPatientVisa = null;
        private FormRegistration.PatientWorkPermit oFormPatientWorkPermit = null;
        private SysFileUpload oFileUpload = null;

        #endregion

        public Default() {

        }

        [Authorization(RoleAction = "fo-registration")]
        public override void Index() {
            string Lob = Convert.ToString(HttpContext.Current.Session["Lob"]).ToUpper();
            if (string.IsNullOrEmpty(Lob) && ConfigurationManager.AppSettings["usinglob"] == "true") {
                //flag
                string url = Data["rooturl"] + "frontoffice/lobselection/?redirectUri=patientdata/default";
                HttpContext.Current.Response.Redirect(url);
            }
            try {
                HttpContext.Current.Session.Remove("appointdkrpt");
                HttpContext.Current.Session.Remove("doctordkrpt");

                Data.Add("Pagetitle", "Search Patient");
                string doctorenkrp = HttpContext.Current.Request["doctorenkrp"].NullSafeToString();
                if (!string.IsNullOrEmpty(doctorenkrp)) {
                    doctordkrpt = KeanuMvc.Reference.CryptoString.Decrypt(doctorenkrp);
                    string[] str = doctordkrpt.Split(';');
                    HttpContext.Current.Session.Add("doctordkrpt", doctordkrpt);
                }
                string appointenkrp = HttpContext.Current.Request["appointenkrp"].NullSafeToString();
                if (!string.IsNullOrEmpty(appointenkrp)) {
                    appointdkrpt = KeanuMvc.Reference.CryptoString.Decrypt(appointenkrp);
                    string[] str = appointdkrpt.Split(';');
                    BookerName = str[1];
                    HttpContext.Current.Session.Add("appointdkrpt", appointdkrpt);
                }
                Data.Add("Patientname", BookerName.NullSafeToString());

                Data.Add("Lob", Lob.ToEnum<HISModels.Enums.StaticVariables.eLOB>().ToString().ToUpper());
                Data.Add("Notification", strNotification);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {
                RenderFile("patient\\searchpatient.html");
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void PatientDetail() {
            try {
                try {
                    HttpContext.Current.Session.Remove("oPatient");
                } catch { }
                #region instantiation
                oPatient = new Patient(); Utils.Helper.SetNullToEmptyString(oPatient);
                oPatientData = new VPatientData(); Utils.Helper.SetNullToEmptyString(oPatientData);
                oPresentAddress = new Address(); Utils.Helper.SetNullToEmptyString(oPresentAddress);
                oPermanentAddress = new Address(); Utils.Helper.SetNullToEmptyString(oPermanentAddress);
                oPatientPrimaryPayer = new PatientPayer(); Utils.Helper.SetNullToEmptyString(oPatientPrimaryPayer);
                oPatientSecondaryPayer = new PatientPayer(); Utils.Helper.SetNullToEmptyString(oPatientSecondaryPayer);
                oPatientTertieryPayer = new PatientPayer(); Utils.Helper.SetNullToEmptyString(oPatientTertieryPayer);
                oFormPresentAddress = new FormRegistration.PresentAddress(); Utils.Helper.SetNullToEmptyString(oFormPresentAddress);
                oFormPermanentAddress = new FormRegistration.PermanentAddress();
                #endregion
                Data.Add("Pagetitle", "Patient Data Registration");

                string patientname = Convert.ToString(HttpContext.Current.Request["qspatientname"]);
                if (!string.IsNullOrEmpty(patientname)) {
                    string patientName = KeanuMvc.Reference.CryptoString.Decrypt(patientname);
                    string[] name = patientName.Split(' ');
                    for (int i = 0; i < name.Length; i++) {
                        if (i == 0) {
                            oPatient.FirstName = name[i];
                        } else if (i == 1) {
                            oPatient.MiddleName = name[i];
                        } else if (i == 2) {
                            oPatient.LastName = name[i];
                        } else {
                            oPatient.LastName += " " + name[i];
                        }
                    }
                }
                
                string PatientId = HttpContext.Current.Request["PatientId"].NullSafeToString();
                
                #region Get By Appointment
                appointdkrpt = HttpContext.Current.Session["appointdkrpt"].NullSafeToString();
                if (!string.IsNullOrEmpty(appointdkrpt)) {
                    string[] strappointment = appointdkrpt.Split(';');

                    string[] name = strappointment[1].Split(' ');
                    for (int i = 0; i < name.Length; i++) {
                        if (i == 0) {
                            oPatient.FirstName = name[i];
                        } else if (i == 1) {
                            oPatient.MiddleName = name[i];
                        } else if (i == 2) {
                            oPatient.LastName = name[i];
                        } else {
                            oPatient.LastName += " " + name[i];
                        }
                    }
                    oFormPresentAddress.PresentAddressDesc = strappointment[4];
                    oPatient.PhoneNumber = strappointment[5];
                    TempPhone = oPatient.PhoneNumber;
                } 

                #endregion

                //Get Data Patient
                if (!string.IsNullOrEmpty(PatientId)) {
                    PatientId = CryptoString.Decrypt(PatientId);
                    string strUri = Global.ServiceUriDictionary["patient"] + PatientId + Global.ServiceUriDictionary["requestformat"];
                    stringReader = base.RestService.GetJson(strUri);
                    oPatientData = JsonConvert.DeserializeObject<VPatientData>(stringReader.ReadToEnd());
                    oPatient = oPatientData.Patient;

                    Utils.Helper.SetNullToEmptyString(oPatient);
                    if (!string.IsNullOrEmpty(TempPhone)) {
                        oPatient.PhoneNumber = TempPhone;
                    }
                    if (oPatient.Birthdate != null) {
                        Data.Add("Age", Utils.Helper.GetAge(oPatient.Birthdate));
                        Data.Add("Birthdate", oPatient.Birthdate.ToString("dd/MM/yyyy"));
                    }
                } else {
                        Data.Add("Age", string.Empty);
                        Data.Add("Birthdate", string.Empty);
                }
                //Gender
                if (oPatient.GenderId == 1) {
                    Data.Add("Gender", "Male");
                } else if (oPatient.GenderId == 2) {
                    Data.Add("Gender", "Female");
                } else { Data.Add("Gender", string.Empty); }

                string weight = oPatient.Weight.NullSafeToString();
                weight=weight.Replace(",", ".");
                string height = oPatient.Height.NullSafeToString();
                height=height.Replace(",",".");

                //Weight Height
                Data.Add("Weight", weight);
                Data.Add("Height", height);
                int iLob = Convert.ToInt32(HttpContext.Current.Session["Lob"]);


                #region Address
                if (oPatientData.ViewDataAddress != null) {
                    foreach (var item in oPatientData.ViewDataAddress) {
                        if (item.TypeId == 1) {
                            oFormPresentAddress.HiddenPresentAddressId = item.AddressId;
                            oFormPresentAddress.PresentAddressDesc = item.AddressDesc;
                            oFormPresentAddress.HiddenPresentAddressAreaId = item.AreaId;
                            oFormPresentAddress.HiddenPresentAddressCityId = item.CityId;
                            oFormPresentAddress.HiddenPresentProvinceId = item.ProvinceId;
                            oFormPresentAddress.HiddenPresentAddressCountryId = item.CountryId;
                            oFormPresentAddress.PresentZipCode = item.ZipCode;
                            oFormPresentAddress.PresentPhoneNumber = item.PhoneNumber;

                            oFormPresentAddress.PresentAreaName = item.AreaName;
                            oFormPresentAddress.PresentCityName = item.CityName;
                            oFormPresentAddress.PresentProvinceName = item.ProvinceName;
                            oFormPresentAddress.PresentCountryName = item.CountryName;

                        }

                        if (item.TypeId == 2) {
                            oFormPermanentAddress.HiddenPermanentAddressId = item.AddressId;
                            oFormPermanentAddress.PermanentAddressDesc = item.AddressDesc;
                            oFormPermanentAddress.HiddenPermanentAddressAreaId = item.AreaId;
                            oFormPermanentAddress.HiddenPermanentAddressCityId = item.CityId;
                            oFormPermanentAddress.HiddenPermanentProvinceId = item.ProvinceId;
                            oFormPermanentAddress.HiddenPermanentAddressCountryId = item.CountryId;
                            oFormPermanentAddress.PermanentZipCode = item.ZipCode;
                            oFormPermanentAddress.PermanentPhoneNumber = item.PhoneNumber;

                            oFormPermanentAddress.PermanentAreaName = item.AreaName;
                            oFormPermanentAddress.PermanentCityName = item.CityName;
                            oFormPermanentAddress.PermanentProvinceName = item.ProvinceName;
                            oFormPermanentAddress.PermanentCountryName = item.CountryName;
                        }
                    }
                }
               

                Utils.Helper.SetNullToEmptyString(oFormPresentAddress);
                Utils.Helper.SetNullToEmptyString(oFormPermanentAddress);

                Data.Add("oFormPresentAddress", oFormPresentAddress);
                Data.Add("oFormPermanentAddress", oFormPermanentAddress);

                #endregion Address

                #region Patient
                Data.Add("DdIdentityCardType", Utils.Helper.GetIdentityCardType("IdentityCardTypeId", oPatient.IdentityCardTypeId.ToString()).NullSafeToString());
                Data.Add("DdSalutation", Utils.Helper.GetSalutation("SalutationId", oPatient.SalutationId.ToString()).NullSafeToString());
                Data.Add("DdOccupation", Utils.Helper.GetOccupation("OccupationId", oPatient.OccupationId.ToString()).NullSafeToString());
                Data.Add("DdBloodType", Utils.Helper.GetBloodType("BloodTypeId","class='required'", oPatient.BloodTypeId.ToString()).NullSafeToString());
                Data.Add("DdBloodTypeNotRequired", Utils.Helper.GetBloodType("BloodTypeId", string.Empty, oPatient.BloodTypeId.ToString()).NullSafeToString());
                #endregion

                #region Patient Additional Profile Etc Info
                Data.Add("DdEthnic", Utils.Helper.GetEthnic("EthnicityId", oPatient.EthnicityId.ToString()).NullSafeToString());
                Data.Add("DdMaritalStatus", Utils.Helper.GetMaritalStatus("MaritalId", oPatient.MaritalId.ToString()).NullSafeToString());
                Data.Add("DdEducation", Utils.Helper.GetEducation("EducationId", oPatient.EducationId.ToString()).NullSafeToString());
                Data.Add("DdReligion", Utils.Helper.GetReligion("ReligionId", oPatient.ReligionId.ToString()).NullSafeToString());
                #endregion

                #region Patient Payer
                FormRegistration.PrimaryPayer oFormPrimaryPayer = new FormRegistration.PrimaryPayer(); Utils.Helper.SetNullToEmptyString(oFormPrimaryPayer);
                FormRegistration.SecondaryPayer oFormSecondaryPayer = new FormRegistration.SecondaryPayer(); Utils.Helper.SetNullToEmptyString(oFormSecondaryPayer);
                FormRegistration.TertieryPayer oFormTertieryPayer = new FormRegistration.TertieryPayer(); Utils.Helper.SetNullToEmptyString(oFormTertieryPayer);

                List<PatientPayer> lsPayer = new List<PatientPayer>();
                foreach (var item in oPatient.PatientPayers) {
                    if (item.Id != 0) { lsPayer.Add(item); }
                }
                for (int i = 0; i < lsPayer.Count; i++) {
                    if (i == 0) {
                        oFormPrimaryPayer.PrimaryPayerId = lsPayer[0].Id;

                        if (lsPayer[0].Bank != null) {
                            oFormPrimaryPayer.PrimaryPayerCategoryId = (int)lsPayer[0].Bank.CategoryId;
                            oFormPrimaryPayer.PrimaryPayerCategoryName = lsPayer[0].Bank.RefPayerCategory.NameValue;
                            oFormPrimaryPayer.HiddenPrimaryBankInsuranceId = (int)lsPayer[0].Bank.Id;

                            foreach(var item in lsPayer[0].Bank.Addresses){
                                oFormPrimaryPayer.HiddenPrimaryPayerAddressId = item.Id;
                                oFormPrimaryPayer.PrimaryPayerFax = item.Fax;
                                oFormPrimaryPayer.PrimaryPayerAddressDesc = item.AddressDesc;
                                oFormPrimaryPayer.PrimaryPayerPhoneNumber = item.PhoneNumber; 
                            }
                          
                        }
                        if (lsPayer[0].Insurance != null) {
                            oFormPrimaryPayer.PrimaryPayerCategoryId = (int)lsPayer[0].Insurance.CategoryId;
                            oFormPrimaryPayer.PrimaryPayerCategoryName = lsPayer[0].Insurance.RefPayerCategory.NameValue;
                            oFormPrimaryPayer.HiddenPrimaryBankInsuranceId = (int)lsPayer[0].Insurance.Id;

                            foreach (var item in lsPayer[0].Insurance.Addresses) {
                                oFormPrimaryPayer.HiddenPrimaryPayerAddressId = item.Id;
                                oFormPrimaryPayer.PrimaryPayerFax = item.Fax;
                                oFormPrimaryPayer.PrimaryPayerAddressDesc = item.AddressDesc;
                                oFormPrimaryPayer.PrimaryPayerPhoneNumber = item.PhoneNumber;
                            }
                           
                        }
                        oFormPrimaryPayer.PrimaryPayerName = lsPayer[0].PayerName;
                        oFormPrimaryPayer.PrimaryPayerValidFrom = lsPayer[0].ValidFrom != null ? lsPayer[0].ValidFrom.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                        oFormPrimaryPayer.PrimaryPayerValidTo = lsPayer[0].ValidTo != null ? lsPayer[0].ValidTo.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                        oFormPrimaryPayer.PrimaryPayerInsuranceNumber = lsPayer[0].InsuranceNumber;
                        oFormPrimaryPayer.HiddenPrimaryIsEmployee = lsPayer[0].EmployeeStatus;
                        oFormPrimaryPayer.PrimaryPayerEmployeeId = lsPayer[0].EmployeeNumber;
                       

                    }
                    if (i == 1) {
                        oFormSecondaryPayer.SecondaryPayerId = lsPayer[1].Id;
                        if (lsPayer[1].Bank != null) {
                            oFormSecondaryPayer.SecondaryPayerCategoryId = (int)lsPayer[1].Bank.CategoryId;
                            oFormSecondaryPayer.SecondaryPayerCategoryName = lsPayer[1].Bank.RefPayerCategory.NameValue;
                            oFormSecondaryPayer.HiddenSecondaryBankInsuranceId = (int)lsPayer[1].Bank.Id;
                            foreach (var item in lsPayer[1].Bank.Addresses) {
                                oFormSecondaryPayer.HiddenSecondaryPayerAddressId = item.Id;
                                oFormSecondaryPayer.SecondaryPayerFax = item.Fax;
                                oFormSecondaryPayer.SecondaryPayerAddressDesc = item.AddressDesc;
                                oFormSecondaryPayer.SecondaryPayerPhoneNumber = item.PhoneNumber;
                            }
                          
                        }
                        if (lsPayer[1].Insurance != null) {
                            oFormSecondaryPayer.SecondaryPayerCategoryId = (int)lsPayer[1].Insurance.CategoryId;
                            oFormSecondaryPayer.SecondaryPayerCategoryName = lsPayer[1].Insurance.RefPayerCategory.NameValue;
                            oFormSecondaryPayer.HiddenSecondaryBankInsuranceId = (int)lsPayer[1].Insurance.Id;

                            foreach (var item in lsPayer[1].Insurance.Addresses) {
                                oFormSecondaryPayer.HiddenSecondaryPayerAddressId = item.Id;
                                oFormSecondaryPayer.SecondaryPayerFax = item.Fax;
                                oFormSecondaryPayer.SecondaryPayerAddressDesc = item.AddressDesc;
                                oFormSecondaryPayer.SecondaryPayerPhoneNumber = item.PhoneNumber;
                            }
                        }

                        oFormSecondaryPayer.SecondaryPayerName = lsPayer[1].PayerName;
                        oFormSecondaryPayer.SecondaryPayerValidFrom = lsPayer[1].ValidFrom != null ? lsPayer[1].ValidFrom.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                        oFormSecondaryPayer.SecondaryPayerValidTo = lsPayer[1].ValidTo != null ? lsPayer[1].ValidTo.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                        oFormSecondaryPayer.SecondaryPayerInsuranceNumber = lsPayer[1].InsuranceNumber;
                        oFormSecondaryPayer.HiddenSecondaryIsEmployee = lsPayer[1].EmployeeStatus;
                        oFormSecondaryPayer.SecondaryPayerEmployeeId = lsPayer[1].EmployeeNumber;
                       

                    }
                    if (i == 2) {
                        oFormTertieryPayer.TertieryPayerId = lsPayer[2].Id;
                        if (lsPayer[2].Bank != null) {
                            oFormTertieryPayer.TertieryPayerCategoryId = (int)lsPayer[2].Bank.CategoryId;
                            oFormTertieryPayer.TertieryPayerCategoryName = lsPayer[2].Bank.RefPayerCategory.NameValue;
                            oFormTertieryPayer.HiddenTertieryBankInsuranceId = (int)lsPayer[2].Bank.Id;
                            foreach (var item in lsPayer[2].Bank.Addresses) {
                                oFormTertieryPayer.HiddenTertieryPayerAddressId = item.Id;
                                oFormTertieryPayer.TertieryPayerFax = item.Fax;
                                oFormTertieryPayer.TertieryPayerAddressDesc = item.AddressDesc;
                                oFormTertieryPayer.TertieryPayerPhoneNumber = item.PhoneNumber;
                            }
                            
                        }
                        if (lsPayer[2].Insurance != null) {
                            oFormTertieryPayer.TertieryPayerCategoryId = (int)lsPayer[2].Insurance.CategoryId;
                            oFormTertieryPayer.TertieryPayerCategoryName = lsPayer[2].Insurance.RefPayerCategory.NameValue;
                            oFormTertieryPayer.HiddenTertieryBankInsuranceId = (int)lsPayer[2].Insurance.Id;
                            foreach (var item in lsPayer[2].Insurance.Addresses) {
                                oFormTertieryPayer.HiddenTertieryPayerAddressId = item.Id;
                                oFormTertieryPayer.TertieryPayerFax = item.Fax;
                                oFormTertieryPayer.TertieryPayerAddressDesc = item.AddressDesc;
                                oFormTertieryPayer.TertieryPayerPhoneNumber = item.PhoneNumber;
                            }
                        }

                        oFormTertieryPayer.TertieryPayerName = lsPayer[2].PayerName;
                        oFormTertieryPayer.TertieryPayerValidFrom = lsPayer[2].ValidFrom != null ? lsPayer[2].ValidFrom.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                        oFormTertieryPayer.TertieryPayerValidTo = lsPayer[2].ValidTo != null ? lsPayer[2].ValidTo.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                        oFormTertieryPayer.TertieryPayerInsuranceNumber = lsPayer[2].InsuranceNumber;
                        oFormTertieryPayer.HiddenTertieryIsEmployee = lsPayer[2].EmployeeStatus;
                        oFormTertieryPayer.TertieryPayerEmployeeId = lsPayer[2].EmployeeNumber;
                        
                    }
                }
                Utils.Helper.SetNullToEmptyString(oFormPrimaryPayer);
                Utils.Helper.SetNullToEmptyString(oFormSecondaryPayer);
                Utils.Helper.SetNullToEmptyString(oFormTertieryPayer);
                Data.Add("oFormPrimaryPayer", oFormPrimaryPayer);
                Data.Add("oFormSecondaryPayer", oFormSecondaryPayer);
                Data.Add("oFormTertieryPayer", oFormTertieryPayer);

                //Data.Add("DdPrimaryPatientPayer", Utils.Helper.GetPatientPayer("PrimaryPayerCategoryId", "class=required", oFormPrimaryPayer.PrimaryPayerCategoryId.ToString()).NullSafeToString());
                //Data.Add("DdSecondaryPatientPayer", Utils.Helper.GetPatientPayer("SecondaryPayerCategoryId", string.Empty, oFormSecondaryPayer.SecondaryPayerCategoryId.ToString()).NullSafeToString());
                //Data.Add("DdTertieryPatientPayer", Utils.Helper.GetPatientPayer("TertieryPayerCategoryId", string.Empty, oFormTertieryPayer.TertieryPayerCategoryId.ToString()).NullSafeToString());

                #endregion

                #region Family and Other Contact
                FormRegistration.PatientRelative oFormPatientRelative = new FormRegistration.PatientRelative();

                foreach (var item in oPatient.PatientRelatives) {
                    #region FamilyRelative
                    if (item.FamilyRelativeTypeId != null) {
                        if (item.FamilyRelativeTypeId == 6 && item.Addresses.Count == 0) {
                            oFormPatientRelative.FatherId = item.Id;
                            oFormPatientRelative.Fathername = item.FirstName;
                        } else if (item.FamilyRelativeTypeId == 5 && item.Addresses.Count == 0) {
                            oFormPatientRelative.MotherId = item.Id;
                            oFormPatientRelative.Mothername = item.FirstName;
                        } else if ((item.Addresses.Count == 0) && (item.FamilyRelativeTypeId == 3 || item.FamilyRelativeTypeId == 4)) {
                            oFormPatientRelative.SpouseId = item.Id;
                            oFormPatientRelative.Spousename = item.FirstName;
                        } else {
                            oFormPatientRelative.FamilyRelativeId = item.Id;
                            oFormPatientRelative.FamilyRelativeTypeId = item.FamilyRelativeTypeId;
                            oFormPatientRelative.FamilyRelativeName = item.FirstName;

                            if (item.Addresses != null) {
                                foreach (var itemaddr in item.Addresses) {
                                    oFormPatientRelative.FamilyRelativeAddress = itemaddr.AddressDesc;
                                    oFormPatientRelative.FamilyRelativeAddressId = itemaddr.Id;
                                }
                            }

                            oFormPatientRelative.FamilyRelativePhone = item.PhoneNumber;
                            oFormPatientRelative.FamilyRelativeMobilephone = item.MobilePhoneNumber;
                            oFormPatientRelative.FamilyRelativeEmail = item.Email;
                            oFormPatientRelative.FamilyRelativeTypeId = Convert.ToInt32(item.FamilyRelativeTypeId);
                            oFormPatientRelative.FamilyRelativeNote = item.Note;
                        }
                    }
                    #endregion
                    #region Other Relative
                    if (item.OthRelativeTypeId != null) {
                        oFormPatientRelative.OtherRelativeId = item.Id;
                        oFormPatientRelative.OtherRelativeTypeId = item.OthRelativeTypeId;
                        oFormPatientRelative.OtherRelativeName = item.FirstName;
                        if (item.Addresses != null) {
                            foreach (var itemaddr in item.Addresses) {
                                oFormPatientRelative.OtherRelativeAddress = itemaddr.AddressDesc;
                                oFormPatientRelative.OtherRelativeAddressId = itemaddr.Id;
                            }
                        }
                        oFormPatientRelative.OtherRelativePhone = item.PhoneNumber;
                        oFormPatientRelative.OtherRelativeMobilephone = item.MobilePhoneNumber;
                        oFormPatientRelative.OtherRelativeEmail = item.Email;
                        oFormPatientRelative.OtherRelativeTypeId = Convert.ToInt32(item.OthRelativeTypeId);
                        oFormPatientRelative.OtherRelativeNote = item.Note;
                    }
                    #endregion
                }

                Utils.Helper.SetNullToEmptyString(oFormPatientRelative);
                Data.Add("oFormPatientRelative", oFormPatientRelative);
                Data.Add("DdFamilyRelative", Utils.Helper.GetFamilyRelative("FamilyRelativeTypeId", oFormPatientRelative.FamilyRelativeTypeId.ToString()).NullSafeToString());
                Data.Add("DdRelative", Utils.Helper.GetRelative("OtherRelativeTypeId", oFormPatientRelative.OtherRelativeTypeId.ToString()).NullSafeToString());
                #endregion

                #region Passport
                oFormPatientPassport = new FormRegistration.PatientPassport(); Utils.Helper.SetNullToEmptyString(oFormPatientPassport);
                oFormPatientVisa = new FormRegistration.PatientVisa(); Utils.Helper.SetNullToEmptyString(oFormPatientVisa);
                oFormPatientWorkPermit = new FormRegistration.PatientWorkPermit(); Utils.Helper.SetNullToEmptyString(oFormPatientWorkPermit);

                foreach (var item in oPatient.PatientPassIds) {
                    if (item.PatientPassTypeId == 1) {
                        oFormPatientPassport.PassportId = item.Id;
                        if (item.PatientPassTypeId != null) {
                            oFormPatientPassport.PatientPassportTypeId = (int)item.PatientPassTypeId;
                        }
                        oFormPatientPassport.PassportCodeValue = item.CodeValue;
                        oFormPatientPassport.PassportIssuedDate = item.IssueDate != null ? item.IssueDate.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                        oFormPatientPassport.PassportExpiryDate = item.ExpiryDate != null ? item.ExpiryDate.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                        oFormPatientPassport.PassportIssuedAt = item.IssuedAt;
                        oFormPatientPassport.PassportNationality =(int) item.Nationality;
                    }
                   if (item.PatientPassTypeId == 2) {
                        oFormPatientVisa.VisaId = item.Id;
                        if (item.PatientPassTypeId != null) {
                            oFormPatientVisa.PatientVisaTypeId = (int)item.PatientPassTypeId;
                        }
                        oFormPatientVisa.VisaIssuedMe = item.IssuedMe;
                        oFormPatientVisa.VisaIssuedDate = item.IssueDate != null ? item.IssueDate.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                        oFormPatientVisa.VisaExpiryDate = item.ExpiryDate != null ? item.ExpiryDate.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                        oFormPatientVisa.VisaIssuedBy = item.IssuedBy;
                        if (item.IsForeigner != null) { 
                         oFormPatientVisa.VisaIsForeigner = (int)item.IsForeigner;
                        }
                        
                    }
                   if (item.PatientPassTypeId == 3) {
                       oFormPatientWorkPermit.WorkPermitId = item.Id;
                       if (item.PatientPassTypeId != null) {
                           oFormPatientWorkPermit.PatientWorkPermitTypeId = (int)item.PatientPassTypeId;
                       }
                       oFormPatientWorkPermit.WorkPermitCodeValue = item.CodeValue;
                       oFormPatientWorkPermit.WorkPermitIssuedDate = item.IssueDate != null ? item.IssueDate.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                       oFormPatientWorkPermit.WorkPermitExpiryDate = item.ExpiryDate != null ? item.ExpiryDate.Value.ToString(HISModels.Enums.StaticVariables.DateFormat, null) : string.Empty;
                       oFormPatientWorkPermit.WorkPermitIssuedBy = item.IssuedBy;
                   }

                }

                Data.Add("DdNationality", Utils.Helper.GetCountry("PassportNationality", oFormPatientPassport.PassportNationality.NullSafeToString()));
                Data.Add("oFormPatientPassport", oFormPatientPassport);
                Data.Add("oFormPatientVisa", oFormPatientVisa);
                Data.Add("oFormPatientWorkPermit", oFormPatientWorkPermit);
                #endregion

                #region Photo

                MemoryStream stream = new MemoryStream();
                string dataLocation = Data["rooturl"] + "Images/PatientImages/avatar.jpg";
                string PhotoId = "0";
                foreach (var item in oPatient.SysFileUploads) {
                    string dataPath=HttpContext.Current.Request.PhysicalApplicationPath + "Images\\PatientImages\\" + item.NameValue + "." + item.FileType;

                    if (!File.Exists(dataPath)) {
                        string photoString = item.StreamValue;
                        byte[] image = Convert.FromBase64String(photoString);
                            //(byte[])item.StreamValue;
                        //stream.Write(image, 0, image.Length);
                        File.WriteAllBytes(dataPath, image);
                    }
                    dataLocation = Data["rooturl"] + "Images/PatientImages/" + item.NameValue + "." + item.FileType;
                    PhotoId =Convert.ToString(item.Id);
                }
                Data.Add("PatientPhoto", dataLocation);
                Data.Add("PhotoId", PhotoId);
                #endregion

                Data.Add("oPatient", oPatient);

                Data.Add("Notification", strNotification);
                string Lob = iLob.ToEnum<HISModels.Enums.StaticVariables.eLOB>().ToString().ToUpper();
                Data.Add("Lob", Lob);
                Data.Add("Actionform", Data["rooturl"] + "patientdata/default/patientdetailpost");
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);

                oPatient = new Patient(); Utils.Helper.SetNullToEmptyString(oPatient);
                oFormPresentAddress = new FormRegistration.PresentAddress(); Utils.Helper.SetNullToEmptyString(oFormPresentAddress);
                oFormPermanentAddress = new FormRegistration.PermanentAddress(); Utils.Helper.SetNullToEmptyString(oFormPermanentAddress);
                FormRegistration.PrimaryPayer oFormPrimaryPayer = new FormRegistration.PrimaryPayer(); Utils.Helper.SetNullToEmptyString(oFormPrimaryPayer);
                FormRegistration.SecondaryPayer oFormSecondaryPayer = new FormRegistration.SecondaryPayer(); Utils.Helper.SetNullToEmptyString(oFormSecondaryPayer);
                FormRegistration.TertieryPayer oFormTertieryPayer = new FormRegistration.TertieryPayer(); Utils.Helper.SetNullToEmptyString(oFormTertieryPayer);
                FormRegistration.PatientRelative oFormPatientRelative = new FormRegistration.PatientRelative(); Utils.Helper.SetNullToEmptyString(oFormPatientRelative);
                oFormPatientPassport = new FormRegistration.PatientPassport(); Utils.Helper.SetNullToEmptyString(oFormPatientPassport);
                oFormPatientVisa = new FormRegistration.PatientVisa(); Utils.Helper.SetNullToEmptyString(oFormPatientVisa);
                oFormPatientWorkPermit = new FormRegistration.PatientWorkPermit(); Utils.Helper.SetNullToEmptyString(oFormPatientWorkPermit);
                
                Data["Pagetitle"]= "Patient Data Registration";
                Data["oPatient"]= oPatient;
                Data["oFormPresentAddress"]= oFormPresentAddress;
                Data["oFormPermanentAddress"]= oFormPermanentAddress;
                Data["oFormPrimaryPayer"]= oFormPrimaryPayer;
                Data["oFormSecondaryPayer"]= oFormSecondaryPayer;
                Data["oFormTertieryPayer"]= oFormTertieryPayer;
                Data["oFormPatientRelative"]= oFormPatientRelative;
                Data["oFormPatientPassport"]= oFormPatientPassport;
                Data["oFormPatientVisa"]= oFormPatientVisa;
                Data["oFormPatientWorkPermit"]= oFormPatientWorkPermit;
                Data["DdNationality"]= Utils.Helper.GetCountry("PassportNationality",string.Empty);
                Data["Age"]= string.Empty;
                Data["Birthdate"]= string.Empty;
                Data["Gender"]= string.Empty;
                Data["Weight"]= string.Empty;
                Data["Height"]= string.Empty;
                Data["Lob"]= string.Empty;
                Data["DdIdentityCardType"]= Utils.Helper.GetIdentityCardType("IdentityCardTypeId", string.Empty);
                Data["DdSalutation"]= Utils.Helper.GetSalutation("SalutationId", string.Empty);
                Data["DdOccupation"]= Utils.Helper.GetOccupation("OccupationId", string.Empty);
                Data["DdBloodType"]= Utils.Helper.GetBloodType("BloodTypeId", "class='required'", string.Empty);
                Data["DdBloodTypeNotRequired"]= Utils.Helper.GetBloodType("BloodTypeId", string.Empty, string.Empty);
                Data["DdEthnic"]= Utils.Helper.GetEthnic("EthnicityId", string.Empty);
                Data["DdMaritalStatus"]= Utils.Helper.GetMaritalStatus("MaritalId", string.Empty);
                Data["DdEducation"]= Utils.Helper.GetEducation("EducationId", string.Empty);
                Data["DdReligion"]= Utils.Helper.GetReligion("ReligionId", string.Empty);
                Data["DdFamilyRelative"]= Utils.Helper.GetFamilyRelative("FamilyRelativeTypeId", string.Empty);
                Data["DdRelative"]= Utils.Helper.GetRelative("OtherRelativeTypeId", string.Empty);
                Data["PatientPhoto"] = Data["rooturl"] + "Images/PatientImages/avatar.jpg";
                Data["PhotoId"]= "0";
                Data["Actionform"]= Data["rooturl"] + "patientdata/default/patientdetailpost";
            } finally {
                RenderFile("patient\\patientregistration.html");
                base.RestService.Dispose();
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void PatientDetailPost() {
            string returnValue = string.Empty;
            string mrn = string.Empty;
            try {
                #region Server Side Validation
                Validations validation = new Validations();
                Array[] arrValidation = new Array[]{
                            new string[]{"FirstName", "FirstName", "required"}
                        };
                validation.Fields = arrValidation;
                strNotification = validation.Run();
                #endregion ServerSide Validation

                strNotification = strNotification != string.Empty ? strNotification = Helper.ErrorMessage(strNotification) : string.Empty;
                if (strNotification == string.Empty) {

                    #region object instantiation
                    oPatient = new Patient(); Utils.Helper.SetNullToEmptyString(oPatient);
                    oPresentAddress = new Address(); Utils.Helper.SetNullToEmptyString(oPresentAddress);
                    oPermanentAddress = new Address(); Utils.Helper.SetNullToEmptyString(oPermanentAddress);
                    Appointment oAppointment = new Appointment();

                    #endregion

                    #region Patient
                    oPatient.PostHandler<Patient>();
                    System.Globalization.NumberFormatInfo info = new System.Globalization.NumberFormatInfo();
                    info.NumberDecimalSeparator = ".";
                    info.NumberGroupSeparator = ",";
                    if (!string.IsNullOrEmpty(HttpContext.Current.Request["Birthdate"])) {
                        oPatient.Birthdate = DateTime.ParseExact(HttpContext.Current.Request["Birthdate"].ToString(), HISModels.Enums.StaticVariables.DateFormat, null);
                    } 
                    if(!string.IsNullOrEmpty(HttpContext.Current.Request["Weight"])){
                        string weight = Convert.ToString(HttpContext.Current.Request["Weight"]);
                        weight= weight.Replace(",", ".");
                        oPatient.Weight=Convert.ToDouble(weight,info);     
                    }
                    if(!string.IsNullOrEmpty(HttpContext.Current.Request["Height"])){
                        string height=Convert.ToString(HttpContext.Current.Request["Height"]);
                        height= height.Replace(",", ".");
                        oPatient.Height = Convert.ToDouble(height, info);
                    }
                    
                    #endregion

                    #region Address
                    FormRegistration.PresentAddress oFormPresentAddress = new FormRegistration.PresentAddress();
                    Utils.Helper.SetNullToEmptyString(oFormPresentAddress);
                    FormRegistration.PermanentAddress oFormPermanentAddress = new FormRegistration.PermanentAddress();
                    Utils.Helper.SetNullToEmptyString(oFormPermanentAddress);

                    oFormPresentAddress.PostHandler<FormRegistration.PresentAddress>();
                    oFormPermanentAddress.PostHandler<FormRegistration.PermanentAddress>();

                    if (!string.IsNullOrEmpty(oFormPresentAddress.PresentAddressDesc)) {
                        oPresentAddress.Id = oFormPresentAddress.HiddenPresentAddressId;
                        oPresentAddress.AddressDesc = oFormPresentAddress.PresentAddressDesc;
                        oPresentAddress.AreaId = oFormPresentAddress.HiddenPresentAddressAreaId;
                        oPresentAddress.CityId = oFormPresentAddress.HiddenPresentAddressCityId;
                        oPresentAddress.ProvinceId = oFormPresentAddress.HiddenPresentProvinceId;
                        oPresentAddress.CountryId = oFormPresentAddress.HiddenPresentAddressCountryId;
                        oPresentAddress.ZipCode = oFormPresentAddress.PresentZipCode;
                        oPresentAddress.PhoneNumber = oFormPresentAddress.PresentPhoneNumber;
                        oPresentAddress.TypeId = 1;
                        oPresentAddress.RecordStatus = 1;
                        oPresentAddress.PatientId = oPatient.Id;

                        oPatient.Addresses.Add(oPresentAddress);
                    }
                    if (!string.IsNullOrEmpty(oFormPermanentAddress.PermanentAddressDesc) || oFormPermanentAddress.HiddenPermanentAddressId != 0) {
                        oPermanentAddress.Id = oFormPermanentAddress.HiddenPermanentAddressId;
                        oPermanentAddress.AddressDesc = oFormPermanentAddress.PermanentAddressDesc;
                        oPermanentAddress.AreaId = oFormPermanentAddress.HiddenPermanentAddressAreaId;
                        oPermanentAddress.CityId = oFormPermanentAddress.HiddenPermanentAddressCityId;
                        oPermanentAddress.ProvinceId = oFormPermanentAddress.HiddenPermanentProvinceId;
                        oPermanentAddress.CountryId = oFormPermanentAddress.HiddenPermanentAddressCountryId;
                        oPermanentAddress.ZipCode = oFormPermanentAddress.PermanentZipCode;
                        oPermanentAddress.PhoneNumber = oFormPermanentAddress.PermanentPhoneNumber;
                        oPermanentAddress.TypeId = 2;
                        oPermanentAddress.RecordStatus = 1;
                        oPermanentAddress.PatientId = oPatient.Id;

                        oPatient.Addresses.Add(oPermanentAddress);
                    }

                    #endregion Address

                    #region Additional Profile, Family, and Other Relative
                    FormRegistration.PatientRelative oFormPatientRelative = new FormRegistration.PatientRelative();
                    Utils.Helper.SetNullToEmptyString(oFormPatientRelative);
                    oFormPatientRelative.PostHandler<FormRegistration.PatientRelative>();


                    if (!string.IsNullOrEmpty(oFormPatientRelative.Fathername) || oFormPatientRelative.FatherId != 0) {
                        PatientRelative oPatientRelativeFather = new PatientRelative();
                        oPatientRelativeFather.FamilyRelativeTypeId = 6;
                        oPatientRelativeFather.FirstName = oFormPatientRelative.Fathername;
                        oPatientRelativeFather.Id = oFormPatientRelative.FatherId;
                        oPatientRelativeFather.PatientId = oPatient.Id;
                        oPatient.PatientRelatives.Add(oPatientRelativeFather);

                    }
                    if (!string.IsNullOrEmpty(oFormPatientRelative.Mothername) || oFormPatientRelative.MotherId != 0) {
                        PatientRelative oPatientRelativeMother = new PatientRelative();
                        oPatientRelativeMother.FamilyRelativeTypeId = 5;
                        oPatientRelativeMother.FirstName = oFormPatientRelative.Mothername;
                        oPatientRelativeMother.Id = oFormPatientRelative.MotherId;
                        oPatientRelativeMother.PatientId = oPatient.Id;
                        oPatient.PatientRelatives.Add(oPatientRelativeMother);

                    }
                    if (!string.IsNullOrEmpty(oFormPatientRelative.Spousename) || oFormPatientRelative.SpouseId != 0) {
                        PatientRelative oPatientRelativeSpouse = new PatientRelative();
                        if (oPatient.SalutationId == 1) { oPatientRelativeSpouse.FamilyRelativeTypeId = 3; } else if (oPatient.SalutationId == 2) { oPatientRelativeSpouse.FamilyRelativeTypeId = 4; }

                        oPatientRelativeSpouse.Id = oFormPatientRelative.SpouseId;
                        oPatientRelativeSpouse.PatientId = oPatient.Id;
                        oPatientRelativeSpouse.FirstName = oFormPatientRelative.Spousename;
                        oPatient.PatientRelatives.Add(oPatientRelativeSpouse);
                    }

                    if ((!string.IsNullOrEmpty(oFormPatientRelative.FamilyRelativeName) && oFormPatientRelative.FamilyRelativeTypeId != 0 && !string.IsNullOrEmpty(oFormPatientRelative.FamilyRelativeAddress)) || oFormPatientRelative.FamilyRelativeId != 0) {

                        Address oFamilyAddress = new Address();
                        PatientRelative oPatientRelative1 = new PatientRelative();
                        oPatientRelative1.Id = oFormPatientRelative.FamilyRelativeId;
                        oPatientRelative1.FirstName = oFormPatientRelative.FamilyRelativeName;

                        oFamilyAddress.Id = oFormPatientRelative.FamilyRelativeAddressId;
                        oFamilyAddress.AddressDesc = oFormPatientRelative.FamilyRelativeAddress;
                        oFamilyAddress.TypeId = 1;
                        oFamilyAddress.PatientRelativeId = oFormPatientRelative.FamilyRelativeId;
                        oPatientRelative1.Addresses.Add(oFamilyAddress);
                        oPatientRelative1.PhoneNumber = oFormPatientRelative.FamilyRelativePhone;
                        oPatientRelative1.MobilePhoneNumber = oFormPatientRelative.FamilyRelativeMobilephone;
                        oPatientRelative1.Email = oFormPatientRelative.FamilyRelativeEmail;
                        oPatientRelative1.FamilyRelativeTypeId = oFormPatientRelative.FamilyRelativeTypeId;

                        oPatientRelative1.Note = oFormPatientRelative.FamilyRelativeNote;

                        oPatientRelative1.PatientId = oPatient.Id;
                        oPatient.PatientRelatives.Add(oPatientRelative1);
                    }

                    if ((!string.IsNullOrEmpty(oFormPatientRelative.OtherRelativeName) && oFormPatientRelative.OtherRelativeTypeId != 0 && !string.IsNullOrEmpty(oFormPatientRelative.OtherRelativeAddress)) || oFormPatientRelative.OtherRelativeId != 0) {
                        Address oOtherRelativeAddress = new Address();
                        PatientRelative oPatientRelative2 = new PatientRelative();
                        oPatientRelative2.Id = oFormPatientRelative.OtherRelativeId;
                        oPatientRelative2.FirstName = oFormPatientRelative.OtherRelativeName;

                        oOtherRelativeAddress.Id = oFormPatientRelative.OtherRelativeAddressId;
                        oOtherRelativeAddress.AddressDesc = oFormPatientRelative.OtherRelativeAddress;
                        oOtherRelativeAddress.TypeId = 1;
                        oOtherRelativeAddress.PatientRelativeId = oFormPatientRelative.OtherRelativeId;
                        oPatientRelative2.Addresses.Add(oOtherRelativeAddress);

                        oPatientRelative2.PhoneNumber = oFormPatientRelative.OtherRelativePhone;
                        oPatientRelative2.MobilePhoneNumber = oFormPatientRelative.OtherRelativeMobilephone;
                        oPatientRelative2.Email = oFormPatientRelative.OtherRelativeEmail;
                        oPatientRelative2.OthRelativeTypeId = oFormPatientRelative.OtherRelativeTypeId;
                        oPatientRelative2.Note = oFormPatientRelative.OtherRelativeNote;

                        oPatientRelative2.PatientId = oPatient.Id;
                        oPatient.PatientRelatives.Add(oPatientRelative2);
                    }
                    #endregion Additional Profile, Family, and Other Relative

                    #region Patient Payer

                    oPatientPrimaryPayer = new PatientPayer(); Utils.Helper.SetNullToEmptyString(oPatientPrimaryPayer);
                    oPatientSecondaryPayer = new PatientPayer(); Utils.Helper.SetNullToEmptyString(oPatientSecondaryPayer);
                    oPatientTertieryPayer = new PatientPayer(); Utils.Helper.SetNullToEmptyString(oPatientTertieryPayer);
                    Address oPrimaryPayerAddr = new Address(); Utils.Helper.SetNullToEmptyString(oPrimaryPayerAddr);
                    Address oSecondaryPayerAddr = new Address(); Utils.Helper.SetNullToEmptyString(oSecondaryPayerAddr);
                    Address oTertieryPayerAddr = new Address(); Utils.Helper.SetNullToEmptyString(oTertieryPayerAddr);

                    FormRegistration.PrimaryPayer oFormPrimaryPayer = new FormRegistration.PrimaryPayer();
                    FormRegistration.SecondaryPayer oFormSecondaryPayer = new FormRegistration.SecondaryPayer();
                    FormRegistration.TertieryPayer oFormTertieryPayer = new FormRegistration.TertieryPayer();

                    oFormPrimaryPayer.PostHandler<FormRegistration.PrimaryPayer>();
                    oFormSecondaryPayer.PostHandler<FormRegistration.SecondaryPayer>();
                    oFormTertieryPayer.PostHandler<FormRegistration.TertieryPayer>();

                    if (oFormPrimaryPayer.PrimaryPayerCategoryId != 0 || oFormPrimaryPayer.PrimaryPayerId != 0) {
                        oPatientPrimaryPayer.Id = oFormPrimaryPayer.PrimaryPayerId;
                        if (oFormPrimaryPayer.PrimaryPayerCategoryId != 0) {
                             if (oFormPrimaryPayer.PrimaryPayerCategoryId == 2) {
                                 oPatientPrimaryPayer.InsuranceId = oFormPrimaryPayer.HiddenPrimaryBankInsuranceId;
                             }
                             if (oFormPrimaryPayer.PrimaryPayerCategoryId == 4) {
                                 oPatientPrimaryPayer.BankId = oFormPrimaryPayer.HiddenPrimaryBankInsuranceId;
                             }
                             //oPatientPrimaryPayer.CategoryId = oFormPrimaryPayer.PrimaryPayerCategoryId;
                        }
                        
                        oPatientPrimaryPayer.PayerName = oFormPrimaryPayer.PrimaryPayerName;
                        if (!string.IsNullOrEmpty(oFormPrimaryPayer.PrimaryPayerValidFrom)) {
                            oPatientPrimaryPayer.ValidFrom = DateTime.ParseExact(oFormPrimaryPayer.PrimaryPayerValidFrom, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        if (!string.IsNullOrEmpty(oFormPrimaryPayer.PrimaryPayerValidTo)) {
                            oPatientPrimaryPayer.ValidTo = DateTime.ParseExact(oFormPrimaryPayer.PrimaryPayerValidTo, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        oPatientPrimaryPayer.EmployeeStatus = oFormPrimaryPayer.HiddenPrimaryIsEmployee;
                        oPatientPrimaryPayer.EmployeeNumber = oFormPrimaryPayer.PrimaryPayerEmployeeId;
                        oPatientPrimaryPayer.InsuranceNumber = oFormPrimaryPayer.PrimaryPayerInsuranceNumber;
                       
                        oPatientPrimaryPayer.PatientId = oPatient.Id;

                        oPatient.PatientPayers.Add(oPatientPrimaryPayer);
                    }
                    if (oFormSecondaryPayer.SecondaryPayerCategoryId != 0 || oFormSecondaryPayer.SecondaryPayerId != 0) {
                        oPatientSecondaryPayer.Id = oFormSecondaryPayer.SecondaryPayerId;
                        if (oFormSecondaryPayer.SecondaryPayerCategoryId != 0) {
                            //oPatientSecondaryPayer.CategoryId = oFormSecondaryPayer.SecondaryPayerCategoryId;
                            if (oFormSecondaryPayer.SecondaryPayerCategoryId == 2) {
                                oPatientSecondaryPayer.InsuranceId = oFormSecondaryPayer.HiddenSecondaryBankInsuranceId;
                            }
                            if (oFormSecondaryPayer.SecondaryPayerCategoryId == 4) {
                                oPatientSecondaryPayer.BankId = oFormSecondaryPayer.HiddenSecondaryBankInsuranceId;
                            }
                        }

                        oPatientSecondaryPayer.PayerName = oFormSecondaryPayer.SecondaryPayerName;
                        if (!string.IsNullOrEmpty(oFormSecondaryPayer.SecondaryPayerValidFrom)) {
                            oPatientSecondaryPayer.ValidFrom = DateTime.ParseExact(oFormSecondaryPayer.SecondaryPayerValidFrom, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        if (!string.IsNullOrEmpty(oFormSecondaryPayer.SecondaryPayerValidTo)) {
                            oPatientSecondaryPayer.ValidTo = DateTime.ParseExact(oFormSecondaryPayer.SecondaryPayerValidTo, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        oPatientSecondaryPayer.InsuranceNumber = oFormSecondaryPayer.SecondaryPayerInsuranceNumber;
                        oPatientSecondaryPayer.EmployeeStatus = oFormSecondaryPayer.HiddenSecondaryIsEmployee;
                        oPatientSecondaryPayer.EmployeeNumber = oFormSecondaryPayer.SecondaryPayerEmployeeId;

                        oPatientSecondaryPayer.PatientId = oPatient.Id;

                        oPatient.PatientPayers.Add(oPatientSecondaryPayer);
                    }
                    if (oFormTertieryPayer.TertieryPayerCategoryId != 0 || oFormTertieryPayer.TertieryPayerId != 0) {
                        oPatientTertieryPayer.Id = oFormTertieryPayer.TertieryPayerId;
                        if (oFormTertieryPayer.TertieryPayerCategoryId != 0) {
                            //oPatientTertieryPayer.CategoryId = oFormTertieryPayer.TertieryPayerCategoryId;
                            if(oFormTertieryPayer.TertieryPayerCategoryId == 2){
                                oPatientTertieryPayer.InsuranceId = oFormTertieryPayer.HiddenTertieryBankInsuranceId;
                            }
                            if (oFormTertieryPayer.TertieryPayerCategoryId == 4) {
                                oPatientTertieryPayer.BankId = oFormTertieryPayer.HiddenTertieryBankInsuranceId;
                            }
                            
                        }
                        oPatientTertieryPayer.PayerName = oFormTertieryPayer.TertieryPayerName;
                        if (!string.IsNullOrEmpty(oFormTertieryPayer.TertieryPayerValidFrom)) {
                            oPatientTertieryPayer.ValidFrom = DateTime.ParseExact(oFormTertieryPayer.TertieryPayerValidFrom, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        if (!string.IsNullOrEmpty(oFormTertieryPayer.TertieryPayerValidTo)) {
                            oPatientTertieryPayer.ValidTo = DateTime.ParseExact(oFormTertieryPayer.TertieryPayerValidTo, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        oPatientTertieryPayer.InsuranceNumber = oFormTertieryPayer.TertieryPayerInsuranceNumber;
                        oPatientTertieryPayer.EmployeeStatus = oFormTertieryPayer.HiddenTertieryIsEmployee;
                        oPatientTertieryPayer.EmployeeNumber = oFormTertieryPayer.TertieryPayerEmployeeId;

                        oPatientTertieryPayer.PatientId = oPatient.Id;

                        oPatient.PatientPayers.Add(oPatientTertieryPayer);
                    }
                    #endregion Patient Payer

                    #region Passport
                    oPatientPassport = new PatientPassId();
                    oPatientVisa = new PatientPassId();
                    oPatientWorkPermit = new PatientPassId();
                    oFormPatientPassport = new FormRegistration.PatientPassport();
                    oFormPatientVisa = new FormRegistration.PatientVisa();
                    oFormPatientWorkPermit = new FormRegistration.PatientWorkPermit();

                    oFormPatientPassport.PostHandler<FormRegistration.PatientPassport>();
                    oFormPatientVisa.PostHandler<FormRegistration.PatientVisa>();
                    oFormPatientWorkPermit.PostHandler<FormRegistration.PatientWorkPermit>();

                    #region PatientPassport
                    if (!string.IsNullOrEmpty(oFormPatientPassport.PassportCodeValue)) {
                        oPatientPassport.Id = oFormPatientPassport.PassportId;
                        oPatientPassport.PatientPassTypeId = 1;
                        oPatientPassport.CodeValue = oFormPatientPassport.PassportCodeValue;
                        if (!string.IsNullOrEmpty(oFormPatientPassport.PassportIssuedDate)) {
                            oPatientPassport.IssueDate = DateTime.ParseExact(oFormPatientPassport.PassportIssuedDate, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        if (!string.IsNullOrEmpty(oFormPatientPassport.PassportExpiryDate)) {
                            oPatientPassport.ExpiryDate = DateTime.ParseExact(oFormPatientPassport.PassportExpiryDate, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        oPatientPassport.IssuedAt = oFormPatientPassport.PassportIssuedAt;
                        oPatientPassport.Nationality = oFormPatientPassport.PassportNationality;
                        oPatientPassport.PatientId = oPatient.Id;

                        oPatient.PatientPassIds.Add(oPatientPassport);
                    }
                    

                    #endregion

                    #region PatientVisa
                    if (!string.IsNullOrEmpty(oFormPatientVisa.VisaIssuedMe)) {
                        oPatientVisa.Id = oFormPatientVisa.VisaId;
                        oPatientVisa.PatientPassTypeId = 2;
                        oPatientVisa.IssuedMe = oFormPatientVisa.VisaIssuedMe;
                        if (!string.IsNullOrEmpty(oFormPatientVisa.VisaIssuedDate)) {
                            oPatientVisa.IssueDate = DateTime.ParseExact(oFormPatientVisa.VisaIssuedDate, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        if (!string.IsNullOrEmpty(oFormPatientVisa.VisaExpiryDate)) {
                            oPatientVisa.ExpiryDate = DateTime.ParseExact(oFormPatientVisa.VisaExpiryDate, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        oPatientVisa.IssuedBy = oFormPatientVisa.VisaIssuedBy;
                        oPatientVisa.IsForeigner = oFormPatientVisa.VisaIsForeigner;
                        oPatientVisa.PatientId = oPatient.Id;

                        oPatient.PatientPassIds.Add(oPatientVisa);
                    }
                    

                    #endregion

                    #region PatientWorkPermit
                    if (!string.IsNullOrEmpty(oFormPatientWorkPermit.WorkPermitCodeValue)) {
                        oPatientWorkPermit.Id = oFormPatientWorkPermit.WorkPermitId;
                        oPatientWorkPermit.PatientPassTypeId = 3;
                        oPatientWorkPermit.CodeValue = oFormPatientWorkPermit.WorkPermitCodeValue;
                        if (!string.IsNullOrEmpty(oFormPatientWorkPermit.WorkPermitIssuedDate)) {
                            oPatientWorkPermit.IssueDate = DateTime.ParseExact(oFormPatientWorkPermit.WorkPermitIssuedDate, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        if (!string.IsNullOrEmpty(oFormPatientWorkPermit.WorkPermitExpiryDate)) {
                            oPatientWorkPermit.ExpiryDate = DateTime.ParseExact(oFormPatientWorkPermit.WorkPermitExpiryDate, HISModels.Enums.StaticVariables.DateFormat, null);
                        }
                        oPatientWorkPermit.IssuedBy = oFormPatientWorkPermit.WorkPermitIssuedBy;
                        oPatientWorkPermit.PatientId = oPatient.Id;

                        oPatient.PatientPassIds.Add(oPatientWorkPermit);
                    }
                    
                    #endregion

                    #endregion

                    #region Photo
                    if (!string.IsNullOrEmpty(Convert.ToString(HttpContext.Current.Session["PhotoName"]))) {
                        oFileUpload = new SysFileUpload();
                        string fotoType = Convert.ToString(HttpContext.Current.Session["PhotoType"]);
                        fotoType = fotoType.Split('/')[1];
                        int fotoSize = Convert.ToInt32(HttpContext.Current.Session["PhotoSize"]);
                        string fotoName = Convert.ToString(HttpContext.Current.Session["PhotoName"]);
                        byte[] photoFile = (byte[])(HttpContext.Current.Session["PhotoFile"]);
                        oFileUpload.StreamValue =Convert.ToBase64String(photoFile);
                        oFileUpload.NameValue = fotoName;
                        oFileUpload.Title = fotoName;
                        oFileUpload.FileCategoryId = 1;
                        oFileUpload.FileSize = fotoSize;
                        oFileUpload.FileType = fotoType;
                        oFileUpload.Id =Convert.ToInt32(HttpContext.Current.Request["PhotoId"]);
                        oFileUpload.PatientId = oPatient.Id;

                        oPatient.SysFileUploads.Add(oFileUpload);
                    }
                    
                    #endregion

                    HttpContext.Current.Session.Add("oPatient", oPatient);

                    oPatient.RecordStatus = 1;
                    oPatient.IsTreated = false;

                    string strUri = Global.ServiceUriDictionary["patient"] + Global.ServiceUriDictionary["requestformat"];
                    if (oPatient.Id == 0) {
                        stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(oPatient));
                    } else {
                        stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(oPatient));
                    }
                    oPatient = JsonConvert.DeserializeObject<Patient>(stringReader.ReadToEnd());

                    if (oPatient != null) {
                        strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        HttpContext.Current.Session.Remove("PhotoFile");
                        HttpContext.Current.Session.Remove("PhotoName");
                        HttpContext.Current.Session.Remove("PhotoType");
                        HttpContext.Current.Session.Remove("PhotoSize");
                        if (oPatient.Addresses != null) {
                            foreach (var itemaddr in oPatient.Addresses) {
                                if (itemaddr.TypeId == 1) {
                                    HiddenPresentAddressId = itemaddr.Id;
                                }
                                if (itemaddr.TypeId == 2) {
                                    HiddenPermanentAddressId = itemaddr.Id;
                                }
                            }
                        }
                        List<PatientPayer> lsPayer = new List<PatientPayer>();
                        foreach (var item in oPatient.PatientPayers) {
                            if (item.Id != 0) { lsPayer.Add(item); }
                        }
                        for (int i = 0; i < lsPayer.Count; i++) {
                            if (i == 0) {
                                PrimaryPayerId = lsPayer[0].Id;
                            }
                            if (i == 1) {
                                SecondaryPayerId = lsPayer[1].Id;
                            }
                            if (i == 2) {
                                TertieryPayerId = lsPayer[2].Id;
                            }
                        }
                        if (oPatient.PatientRelatives != null) {
                            foreach (var item in oPatient.PatientRelatives) {
                                if (item.FamilyRelativeTypeId != null) {
                                    if (item.FamilyRelativeTypeId == 6 && item.Addresses.Count == 0) {
                                        FatherId = item.Id;
                                    } else if (item.FamilyRelativeTypeId == 5 && item.Addresses.Count == 0) {
                                        MotherId = item.Id;
                                    } else if (item.FamilyRelativeTypeId == 3 || item.FamilyRelativeTypeId == 4) {
                                        SpouseId = item.Id;
                                    } else {
                                        FamilyRelativeId = item.Id;
                                    }
                                }
                                if (item.OthRelativeTypeId != null) {
                                    OtherRelativeId = item.Id;
                                }
                            }
                            
                        }
                        
                        HttpContext.Current.Session.Add("oPatient", oPatient);
                    } else {
                        strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                    }

                }
                returnValue = "{\"strNotification\": \"" + strNotification +
                               "\",\"mrn\": \"" + oPatient.MedicalRecordNumber.NullSafeToString() +
                               "\",\"patientId\": \"" + oPatient.Id.NullSafeToString() +
                               "\",\"HiddenPresentAddressId\": \"" + HiddenPresentAddressId +
                               "\",\"HiddenPermanentAddressId\": \"" + HiddenPermanentAddressId +
                               "\",\"PrimaryPayerId\": \"" + PrimaryPayerId +
                               "\",\"SecondaryPayerId\": \"" + SecondaryPayerId +
                               "\",\"TertieryPayerId\": \"" + TertieryPayerId +
                               "\",\"FatherId\": \"" + FatherId +
                               "\",\"MotherId\": \"" + MotherId +
                               "\",\"SpouseId\": \"" + SpouseId +
                               "\",\"FamilyRelativeId\": \"" + FamilyRelativeId +
                               "\",\"OtherRelativeId\": \"" + OtherRelativeId +
                               "\"}";
                HttpContext.Current.Response.Write(returnValue);

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void TableList() {
            string strJson = string.Empty;
            string sEcho = HttpContext.Current.Request["sEcho"];
            try {
                try {
                    HttpContext.Current.Session.Remove("oPatient");
                } catch {}
                string mrn = HttpContext.Current.Request["mrn"].NullSafeToString();
                string patientname = HttpContext.Current.Request["patientname"].NullSafeToString();
                string dob = HttpContext.Current.Request["dob"].NullSafeToString();
                if (!string.IsNullOrEmpty(dob)) {
                    Match match = Regex.Match(dob, @"^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$", RegexOptions.IgnoreCase);
                    if (!match.Success) {
                        dob = "01/01/0001";
                    }
                }
                string ssearch = "mrn=" + mrn + ";patientname=" + patientname + ";dob=" + dob;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = ssearch;

                string strUri = Global.ServiceUriDictionary["patientpaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));

                ///Convert to JObject
                JObject o = JObject.Parse(stringReader.ReadToEnd());
                JArray aaData = (JArray)o["aaData"];

                ///Modify it
                JArray aaDataModified = new JArray();

                for (int i = 0; i < aaData.Count(); i++) {
                    JObject oo = JObject.Parse(aaData[i].ToString());
                    oo["Id"] = KeanuMvc.Reference.CryptoString.Encrypt(oo["Id"].ToString());
                    DateTime tempDate = (DateTime)oo["Birthdate"];
                    oo["Birthdate"] = tempDate.ToShortIndonesian(false);
                    aaDataModified.Add(oo);
                }
                o["aaData"] = aaDataModified;
                if ((int)o["iTotalDisplayRecords"] == 0) {
                    if (!string.IsNullOrEmpty(patientname)) {
                        o["patientName"] = KeanuMvc.Reference.CryptoString.Encrypt(patientname);
                    }
                }
                ///So serialize
                strJson = JsonConvert.SerializeObject(o);

                stringReader.Dispose();
                base.RestService.Dispose();
            } catch (Exception ex) {
                strJson = "{\"sEcho\":\"" + sEcho + "\",\"iTotalRecords\":0,\"iTotalDisplayRecords\":0,\"ExceptionMessage\":\"Exception Occured : "+ex.Message+"\",\"aaData\":[]}";
            } finally {
                HttpContext.Current.Response.Write(strJson);
            }
        }

        [Authorization(RoleAction = "fo-registration")]
        public void GetClock() {
            string thistime = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"); //Javascript Date Format
            HttpContext.Current.Response.Write(thistime);
        }

        [Authorization(RoleAction = "fo-registration")]
        public void UploadHandler() {
            string fileName = string.Empty;
            try {
                HttpFileCollection files = HttpContext.Current.Request.Files;
                foreach (string fileTagName in files) {
                    HttpPostedFile file = HttpContext.Current.Request.Files[fileTagName];
                    if (file.ContentLength > 0) {
                        int size = file.ContentLength;
                        fileName = file.FileName;
                        int position = fileName.LastIndexOf("\\");
                        fileName = fileName.Substring(position + 1);
                        string contentType = file.ContentType;
                        byte[] fileData = new byte[size];
                        file.InputStream.Read(fileData, 0, size);
                        HttpContext.Current.Session.Add("PhotoFile", fileData);
                        HttpContext.Current.Session.Add("PhotoType", contentType);
                        HttpContext.Current.Session.Add("PhotoSize", size);
                    }
                }

                string[] concatStr = fileName.Split('.');
                string fileExt = concatStr[concatStr.Length - 1];
                Guid msgGuid = System.Guid.NewGuid();
                fileName = DateTime.Today.ToString("dd-MM-yy") + "-" + msgGuid;
                HttpContext.Current.Session.Add("PhotoName", fileName);
                string location = HttpContext.Current.Request.PhysicalApplicationPath + "Images\\PatientImages\\" + fileName + "." + fileExt;
                HttpContext.Current.Request.Files[0].SaveAs(location);
                string result = fileName+"."+fileExt;
                HttpContext.Current.Response.Write(result);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
           

            //UploadHandler oFileUploadHandler = new UploadHandler();
            //try {
            //    oFileUploadHandler.ProcessRequest(HttpContext.Current);
            //    string result = "{\"strNotification\": \"ok\"}";
            //    HttpContext.Current.Response.Write(result);
            //} catch (Exception ex) {
            //    HttpContext.Current.Response.Write(ex.Message);
            //}
        }

    }
}